package info.batcloud.fanli.background.task.scheduler;

import info.batcloud.fanli.core.service.DdkService;
import info.batcloud.fanli.core.service.SystemSettingService;
import info.batcloud.fanli.core.settings.DdkContextSetting;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.inject.Inject;
import java.util.Date;

@Component
public class DdkScheduler {

    @Inject
    private DdkService ddkService;

    @Inject
    private SystemSettingService systemSettingService;

    @PostConstruct
    public void init() {
//        ddkService.refreshAccessToken();
    }

    //每隔2小时刷新一次
    @Scheduled(cron = "0 0 1,12 * * ?")
    public void refreshToken() {
        ddkService.refreshAccessToken();
    }

    @Scheduled(cron = "${cron.ddk.orderFetch}")
    public void fetchOrder() {
        DdkContextSetting ddkContextSetting = systemSettingService.findActiveSetting(DdkContextSetting.class);
        DdkService.OrderFetchParam param = new DdkService.OrderFetchParam();
        Date now = new Date();
        if (ddkContextSetting.getLastOrderFetchEndTime() == null) {
            //如果最后时间为0，那么从当前开始前7天的时间
            param.setStartUpdateTime(DateUtils.addDays(now, -7));
        } else {
            param.setStartUpdateTime(ddkContextSetting.getLastOrderFetchEndTime());
        }

        param.setEndUpdateTime(now);
        ddkContextSetting.setLastOrderFetchEndTime(now);
        ddkService.fetchOrder(param);
        systemSettingService.saveSetting(ddkContextSetting, 0);
        systemSettingService.activeSetting(DdkContextSetting.class, 0);
    }

}
